package com.vteba.shards.table.service;

import org.I0Itec.zkclient.ZkClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.vteba.tx.jdbc.mybatis.cache.ShardsTableCacheService;
import com.vteba.utils.common.Assert;
import com.vteba.utils.common.PropUtils;

public class ShardsTableListener implements InitializingBean {
	private static final Logger LOGGER = LogManager.getLogger(ShardsTableListener.class);
	private ShardsTableCacheService shardsTableCacheService;
	private ZkClient zkClient;

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(shardsTableCacheService, "property [shardsTableCacheService] connot be null.");
		// 没有注入，才去初始化
		if (zkClient == null) {
			String serverList = PropUtils.get("zookeeper.server");
			Assert.notNull(serverList, "config.properties lose 'zookeeper.server'.");

			int connectionTimeout = PropUtils.getInt("zookeeper.timeout", 100000);
			zkClient = new ZkClient(serverList, connectionTimeout);
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("zookeeper server [{}] connected success.", serverList);
			}
		}

		ShardsTableTask task = new ShardsTableTask(zkClient, shardsTableCacheService);
		Thread thread = new Thread(task);
		thread.start();
	}

	public void setShardsTableCacheService(ShardsTableCacheService shardsTableCacheService) {
		this.shardsTableCacheService = shardsTableCacheService;
	}

	public void setZkClient(ZkClient zkClient) {
		this.zkClient = zkClient;
	}

}
